<template>
    <view class="linkbank">
        <view class="linkbank-line linkbank-border">
            <view class="linkbank-label">银行卡号</view>
            <input
                v-model="form.bankAccountNo"
                @input="changeBank"
                class="input"
                placeholder="请填写银行卡号"
                :placeholder-style="'color: #cccc;' + 'font-size:29rpx;' + 'text-align:right;'" />
        </view>
        <view class="linkbank-line linkbank-border">
            <view class="linkbank-label">开户银行</view>
            <input
                v-model="form.bankName"
                class="input-user"
                placeholder="根据银行卡号自动识别"
                :placeholder-style="'color: #cccc;' + 'font-size:29rpx;' + 'text-align:right;'" />
        </view>
        <view class="linkbank-line linkbank-border">
            <view class="linkbank-label">银行预留手机号</view>
            <input
                class="input-two"
                v-model="form.mobile"
                type="number"
                placeholder="请填写手机号"
                :placeholder-style="'color: #cccc;' + 'font-size:29rpx;' + 'text-align:right;'" />
        </view>
        <!-- 商家未开通【宝付账户自动扣款】或者商家已开通【宝付账户自动扣款】卡号为招商时验证码一行隐藏 -->
        <view class="linkbank-line" v-if="props.type == 2 && cardBin != 'CMB'">
            <view class="linkbank-label">验证码</view>
            <view class="linkbank-bet">
                <input
                    class="linkbank-code"
                    v-model="form.verifyCode"
                    type="number"
                    placeholder="请填验证码"
                    :placeholder-style="'color: #cccc;' + 'font-size:29rpx;' + 'text-align:right;'" />
                <view class="linkbank-center"></view>
                <view :class="['code-get', disabled ? 'phone_disabled' : 'phone_enabled']" @click="sendHandler">{{
                    btnText
                }}</view>
            </view>
        </view>
        <view class="linkbank-all">
            <view class="linkbank-save" @click="save">保存</view>
        </view>
        <popup ref="popRef" :showIcons="false">
            <template #content>
                <view class="balance-path">系统已发送短信到您的手机，<br />请点击短信链接进行绑卡</view>
                <view class="pop-line">
                    <view class="pop-btn" @click="checkDone">我已点击短信完成绑卡</view>
                </view>
            </template>
        </popup>
    </view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import popup from '../components/popup.vue';
import { isNotEmpty, isEmpty, isMobile, getImgOssUrl } from '@/commons/utils';
import storage from '@/commons/storage';
import router from '@/router';
import store from '@/store';
import prenv from '@/prenv';
import { loginWxinfoHandler } from '@/hooks';
import request from '@/request';
const props = defineProps(['type']); //2-商家开通【宝付账户自动扣款】1-商家未开通【宝付账户自动扣款】
let form = reactive({ bankName: '', bankAccountNo: '', mobile: '', verifyCode: '' });
let btnText = ref('获取验证码');
const initSecond = 60;
let intervalId = null;
let currentSecond = ref(initSecond);
let cardHolder = ref();
let cardNum = ref();
let popRef = ref();
let time = ref(null);
let cardBin = ref(); //判断是不是招商银行
let status = ref(); // 1 和宝付有交互 2没有交互"
const disabled = computed(() => btnText.value !== '获取验证码');
onShow(async () => {
    if (props.type == 2) {
        const res = await request('accountDetail');
        let data = ['bankName', 'bankAccountNo', 'mobile'];
        data.map(item => (form[item] = res.data[item]));
        cardBin.value = res.data.cardBin;
        status.value = res.data.status;
        if (status.value == 1 && cardBin.value == 'CMB') {
            save();
            // popRef.value.openPopup();
        }
    } else {
        const res = await request('getRealNameServ');
        cardHolder.value = res.data.name;
        cardNum.value = res.data.idNo;
    }
});
/**
 * 设置按钮文本
 */
const setNewText = () => {
    btnText.value = `重新获取(${currentSecond.value}秒)`;
    currentSecond.value--;
    if (currentSecond.value === -1) {
        btnText.value = `获取验证码`;
        clearInterval(intervalId);
        currentSecond.value = initSecond;
    }
};

/**
 * 创建倒计时
 */
const createInterval = () => {
    intervalId = setInterval(setNewText, 1000);
};

/**
 * 执行倒计时
 */
const countdownHandler = () => {
    setNewText();
    createInterval();
};
const checkAllHandler = flag => {
    let title;
    let Data = flag ? [form.bankName, form.bankAccountNo] : [form.bankName, form.bankAccountNo, form.verifyCode];
    let tips = flag
        ? ['请先输入银行卡号', '请先输入开户银行']
        : ['请先输入银行卡号', '请先输入开户银行', '请输入验证码'];
    try {
        Data.forEach((item, index) => {
            if (index == 2 && !checkMobileHandler()) {
                throw new Error(false);
            } else {
                if (isEmpty(Data[index])) {
                    title = tips[index];
                    if (isNotEmpty(title)) {
                        uni.showToast({
                            title,
                            icon: 'none'
                        });
                        throw new Error(false);
                    }
                }
            }
        });
    } catch (err) {
        return JSON.parse(err.message);
    }
    return true;
};

/**
 * 检查手机号
 */
const checkMobileHandler = () => {
    let title;
    const mobile = form.mobile;
    if (isEmpty(mobile)) {
        title = '请先输入手机号';
    } else if (!isMobile(mobile)) {
        title = '请输入正确的手机号';
    }
    if (isNotEmpty(title)) {
        uni.showToast({
            title,
            icon: 'none'
        });
        return false;
    }
    return true;
};
/**
 * 发送短信
 */
const sendHandler = async () => {
    if (!checkMobileHandler()) return;
    if (!disabled.value) {
        const mobile = form.mobile;
        let openid = storage.get('openid');
        if (props.type == 1) {
            if (isEmpty(openid)) {
                const res = await loginWxinfoHandler();
                openid = res.openid;
            }
            request('sendSmsCodeServ', { mobile, openid })
                .then(res => {
                    countdownHandler();
                })
                .catch(e => {
                    uni.showToast({
                        title: e.data.msg,
                        icon: 'none'
                    });
                });
        } else {
            if (!checkAllHandler(true)) return;
            if (!checkMobileHandler()) return;
            request('bindcard', { bankAccountNo: form.bankAccountNo, mobile: form.mobile })
                .then(res => {
                    countdownHandler();
                })
                .catch(e => {
                    uni.showToast({
                        title: e.data.msg,
                        icon: 'none'
                    });
                });
        }
    }
};
const changeBank = val => {
    let param = form.bankAccountNo;
    if (time.value) {
        clearTimeout(time.value);
    }
    time.value = setTimeout(() => {
        request('bankcard', { cardNo: param.replace(/\s*/g, '') }).then(res => {
            form.bankName = res?.data?.data?.bankDescription;
            cardBin.value = res?.data?.data?.bankId;
        });
    }, 500);
};
const checkDone = async () => {
    request('walletCheckBankCard')
        .then(res => {
            if (res.data.cardBin == 'CMB' && res.data.status == 3) {
                popRef.value.closePopup();
                router.redirectTo({ url: '/pages-user/balanceCash/cash/tocard' });
            } else {
                uni.showToast({
                    title: '请先点击短信链接，进行绑卡签约~',
                    icon: 'none'
                });
            }
        })
        .catch(err => {
            uni.showToast({
                title: err.data.msg,
                icon: 'none'
            });
        });
};
const save = () => {
    if (props.type == 1) {
        if (!checkAllHandler(true)) return;
        if (!checkMobileHandler()) return;
        // 四要素校验
        request('bankcardAuth', {
            accNo: form.bankAccountNo,
            idCard: cardNum.value,
            idHolder: cardHolder.value,
            mobile: form.mobile
        }).then(res => {
            if (res.data.code == '0') {
                // 绑卡
                request('bindBankAccount', { ...form, cardBin: cardBin.value, creatMethod: 1 }).then(res => {
                    router.redirectTo({ url: '/pages-user/balanceCash/cash/tocard' });
                });
            } else {
                uni.showToast({
                    title: res.data.desc,
                    icon: 'none'
                });
            }
        });
    } else {
        if (cardBin.value == 'CMB') {
            if (!checkAllHandler(true)) return;
            if (!checkMobileHandler()) return;

            // 招商卡-保存银行卡时 传递returnUrl(前端回调地址)
            // const currentEnv = store.useEnvStore().currentEnv;
            // let url = prenv[currentEnv]['API_BASE_URL']['apigw'] + '/pages-user/balanceCash/cash/tocard';
            request('bindBankAccount', {
                ...form,
                cardBin: cardBin.value,
                returnUrl: '/pages-user/balanceCash/cash/tocard',
                creatMethod: 2
            }).then(res => {
                popRef.value.openPopup();
            });
        } else {
            if (!checkAllHandler(false)) return;
            request('bindBankAccount', { ...form, cardBin: cardBin.value, creatMethod: 2 }).then(res => {
                router.redirectTo({ url: '/pages-user/balanceCash/cash/tocard' });
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.linkbank {
    .balance-path {
        font-size: 29rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #33302d;
        line-height: 44rpx;
    }
    .pop-btn {
        width: 287rpx;
        height: 65rpx;
        line-height: 65rpx;
        text-align: center;
        background: linear-gradient(270deg, #ff5356 0%, #fe292b 100%);
        border-radius: 40rpx;
        font-size: 25rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
    }
    .pop-line {
        margin-top: 50rpx;
        width: 100%;
        display: flex;
        justify-content: center;
    }
    .linkbank-all {
        display: flex;
        justify-content: center;
        .linkbank-save {
            margin-top: 107rpx;
            text-align: center;
            width: 690rpx;
            height: 80rpx;
            background: linear-gradient(270deg, #ff5356 0%, #fe292b 100%);
            font-size: 29rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #ffffff;
            line-height: 80rpx;
            border-radius: 40rpx;
        }
    }

    .linkbank-border {
        border-bottom: 1px solid #f5f5f5;
    }
    .linkbank-line {
        background: #fff;
        padding: 36rpx 29rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .linkbank-bet {
            display: flex;
            align-items: center;
        }
        .linkbank-code {
            width: 152rpx;
            font-size: 29rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            text-align: right;
        }
        .code-get {
            margin-left: 14rpx;
            font-size: 29rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
        }
        .phone_enabled {
            color: #fe292b;
        }
        .phone_disabled {
            color: #999999;
        }
        .linkbank-center {
            margin-left: 12rpx;
            width: 2rpx;
            height: 29rpx;
            background-color: #999999;
        }
        .input {
            text-align: right;
        }
        .input-user {
            text-align: right;
        }
        .input-two {
            text-align: right;
        }
        .linkbank-label {
            padding-right: 10rpx;
            flex-shrink: 0;
            font-size: 29rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
        }

        .linkbank-type {
            font-size: 29rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
        }
    }
}
</style>
